package com.tree.common.interceptor;

import com.tree.common.annotation.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName com.tree.common.interceptor
 * Description: 设置需要返回包装对象的标识
 * <p>
 * 如果类上或者方法上包含ResponseResult注解，则添加标识
 * </p>
 * @Author tree
 * @Date 2020-03-28 23:58
 * @Version 1.0
 */
@Slf4j
public class ResponseResultInterceptor implements HandlerInterceptor {
    /**
     * 标记名称
     */
    public static final String RESPONSE_RESULT_MARK = "RESPONSE_RESULT_MARK";

    /**
     * 就是获取此请求，是否需要返回值包装，设置一个属性标记。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求方法
        if(handler instanceof HandlerMethod){
            final  HandlerMethod handlerMethod = (HandlerMethod) handler;
            final  Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            //判断是否在类对象上加了ResponseResult注解
            if(clazz.isAnnotationPresent(ResponseResult.class)){
                //设置该请求返回体， 需要包装， 往下传递，在ResponseBodyAdvice接口进行判断
                request.setAttribute(RESPONSE_RESULT_MARK,clazz.getAnnotation(ResponseResult.class));
            }
            //方法上是否加了ResponseResult注释
            else if(method.isAnnotationPresent(ResponseResult.class)){
                //设置该请求返回体， 需要包装， 往下传递，在ResponseBodyAdvice接口进行判断
                request.setAttribute(RESPONSE_RESULT_MARK,clazz.getAnnotation(ResponseResult.class));

            }

        }
        return true;
    }
}
